package db

import (
	"core/env"
	"core/rds"
	"core/utils"
	"fmt"
	"strings"
)

type ShareCode struct {
	Uid int64
}

func EncodeShareCode(uid int64) string {
	return utils.Encrypt(ShareCode{Uid: uid}, env.Conf.AppSecret1)
}
func DecodeShareCode(shareCode string) (uid int64) {
	if shareCode == "" {
		return
	}
	shareCodeData := new(ShareCode)
	err := utils.Decrypt(shareCode, env.Conf.AppSecret1, shareCodeData)
	if err != nil {
		utils.Error(err)
		return
	}
	uid = shareCodeData.Uid
	return
}

func encodeInvitee(invitee *Invitee) string {
	return fmt.Sprintf("%t:%d", invitee.GotReward, invitee.InviteAtUnix)
}
func decodeInvitee(uid int64, inviteeStr string) (invitee *Invitee) {
	invitee = new(Invitee)
	fmt.Fscanf(strings.NewReader(inviteeStr), "%t:%d", &invitee.GotReward, &invitee.InviteAtUnix)
	invitee.UID = uid
	return
}

func (u *User) SaveInvitee(invitee *Invitee) (err error) {
	err = rds.GetCacheClient(u.UID).HSet(
		MakeUserKey(u.UID),
		fmt.Sprintf("%s%d", FieldInvitee, invitee.UID),
		encodeInvitee(invitee),
	).Err()
	return
}

type SortInvitees []Invitee

func (a SortInvitees) Len() int           { return len(a) }
func (a SortInvitees) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a SortInvitees) Less(i, j int) bool { return a[i].InviteAtUnix < a[j].InviteAtUnix }
